

#include "WatchDog.h"

#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

static const char *host = "192.168.178.200";
static const short port = 2000;

static int sockfd = 0;
static int connectFlag = 0;
static int heartBeatTime = 3;

static int tcpClientInit()
{
    struct linger ling;
    ling.l_linger = 0;
    ling.l_onoff = 1;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return -1;

    setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char *)&ling, sizeof(ling));

    return sockfd;
}

static void tcpClientConnet(const char *host, const short port)
{
    struct sockaddr_in sAddr;
    struct hostent *hostname = NULL;

    memset(&sAddr, 0, sizeof(struct sockaddr_in));
    sAddr.sin_family = AF_INET;
    sAddr.sin_port = htons(port);

    if ((hostname = gethostbyname(host)) == NULL)
        sAddr.sin_addr.s_addr = inet_addr(host);
    else
        memcpy(&sAddr.sin_addr, hostname->h_addr, hostname->h_length);

    int ret = connect(sockfd, (struct sockaddr *)&sAddr, sizeof(struct sockaddr_in));
    if (0 == ret)
    {
        connectFlag = 1;
    }
    else
    {
        connectFlag = 0;
    }
}

static int tcpClientSend(const void *sendBuf, const int len)
{
    int ret = 0;
    int dataLeft = len;
    int sendTotal = 0;
    while (dataLeft > 0)
    {
        ret = send(sockfd, sendBuf + sendTotal, dataLeft, 0);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
            {
                usleep(10 * 1000);
                ret = 0;
            }
            else
            {
                connectFlag = 0;
                return -1;
            }
        }

        sendTotal += ret;
        dataLeft = len - sendTotal;
    }

    return sendTotal;
}

const char *heartBeatMsg = "@HeartBeat#";
static void *watch_dog_thread(void *args)
{
    while (1)
    {
        if (connectFlag == 0)
        {
            tcpClientConnet(host, port);
        }

        tcpClientSend(heartBeatMsg, strlen(heartBeatMsg));
        printf("Send HeartBeat!\n");
        sleep(heartBeatTime);
    }
}

static void watch_dog_thread_start()
{
    pthread_t ppid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&ppid, &attr, watch_dog_thread, NULL);
}

void init_watch_dog()
{

    int res = tcpClientInit();

    if (res == -1)
    {
        printf("init watch dog failure!\n");
        return;
    }

    watch_dog_thread_start();

}

void send_reboot_cmd(int second)
{
    char cmd[24] = {0};
    snprintf(cmd, 24, "@RST=%ds#", second);
    if (tcpClientSend(cmd, strlen(cmd)) < 0)
    {
        printf("send failure!\n");
    }
    else{
        printf("send %s\n",cmd);
    }
}